package com.wdd.libbase.di

import com.blankj.utilcode.util.AppUtils
import com.lzy.okgo.OkGo
import com.lzy.okgo.cookie.CookieJarImpl
import com.lzy.okgo.cookie.store.MemoryCookieStore
import com.wdd.libbase.di.annotation.GlideOkHttpClient
import com.wdd.stetho.StethoUtils
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * @ProjectName: Tools
 * @Package: com.wdd.tool.di.module
 * @ClassName: HttpClientModule
 * @Description: java类作用描述
 * @Author: 王丹丹
 * @CreateDate: 2019/6/27 11:27
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/6/27 11:27
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Module
class HttpClientModule {
    @Singleton
    @Provides
    fun provideOkHttpBuilder(loggingInterceptor: HttpLoggingInterceptor?): OkHttpClient.Builder {
        val builder = OkHttpClient.Builder()
        if (AppUtils.isAppDebug()) {
            builder.addInterceptor(loggingInterceptor!!)
        }
        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
        builder.connectTimeout(
            OkGo.DEFAULT_MILLISECONDS,
            TimeUnit.MILLISECONDS
        )
        //使用内存保持cookie，app退出后，cookie消失
        builder.cookieJar(CookieJarImpl(MemoryCookieStore()))
        StethoUtils.addStethoNetWork(builder)
        return builder
    }

    @Singleton
    @Provides
    @GlideOkHttpClient
    fun provideGlideOkHttp(loggingInterceptor: HttpLoggingInterceptor?): OkHttpClient.Builder {
        val gliderBuilder = OkHttpClient.Builder()
        if (AppUtils.isAppDebug()) {
            gliderBuilder.addInterceptor(loggingInterceptor!!)
        }
        //超时时间设置，默认60秒
        gliderBuilder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
        gliderBuilder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
        gliderBuilder.connectTimeout(
            OkGo.DEFAULT_MILLISECONDS,
            TimeUnit.MILLISECONDS
        )
        StethoUtils.addStethoNetWork(gliderBuilder)
        return gliderBuilder
    }

    @Singleton
    @Provides
    fun provideOkHttpLogging(): HttpLoggingInterceptor {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return loggingInterceptor
    }
}